package com.hissy.common.zookeeper;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * Created by zhangyanfei on 2019/6/28.
 *
 * @author zhangyanfei
 * @date 2019/06/28
 */
public class ZkClient implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zk = null;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws Exception {
        String path = "/username";
        // 1.开启心跳线程  2.开启事件监听线程
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new ZkClient());
        //等待zk连接成功的通知  连接成功后触发
        connectedSemaphore.await();
        //获取path目录节点的配置数据，并注册默认的监听器
        System.out.println(new String(zk.getData(path, true, stat)));

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        // 连接成功
        if (KeeperState.SyncConnected == watchedEvent.getState()) {
            // 没有任何事件发生
            if (EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()) {
                connectedSemaphore.countDown();
            } else if (watchedEvent.getType() == EventType.NodeDataChanged) {
                //zk目录节点数据变化通知事件
                try {
                    System.out.println("配置已修改，新值为：" + new String(zk.getData(watchedEvent.getPath(), true, stat)));
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     *
     */
}
